/**
   Programa que acessa uma câmera e processa a imagem achando bordas
   com o algoritmo de Canny. Parâmetros da função são manipuláveis
   pela GUI.

   Baseado num programa de:
   Andreas Geiger, Karlsruhe Institute of Technology, 16.7.2007.
*/

#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include <math.h>

#include <iostream>
using namespace std;

CvCapture *capture = 0;		// camera device 
IplImage *frame = 0;		// camera frame
IplImage *output = 0;		// output image (with buttons)
int exit_program = 0;		// exit program? (yes/no)



int thr1, thr2, apperture;


/**
 *  Main function
 */
int
main (int argc, char **argv)
{
  // Welcome message
  printf ("Welcome! OpenCV version: %s (%d.%d.%d)\n", CV_VERSION,
	  CV_MAJOR_VERSION, CV_MINOR_VERSION, CV_SUBMINOR_VERSION);

  // Initialize webcamera
  capture = cvCaptureFromCAM (0);
  if (!capture)
    {
      fprintf (stderr, "Could not initialize capturing. Exiting...\n");
      return -1;
    }

  // Create the Browser Window
  cvNamedWindow ("webcam", 1);

  // Create the Trackbars and set initial values    
  cvCreateTrackbar ("Threshold MC", "webcam", &thr1, 255, NULL);
  cvSetTrackbarPos ("Threshold MC", "webcam", 60);
  cvCreateTrackbar ("Threshold MD", "webcam", &thr2, 255, NULL);
  cvSetTrackbarPos ("Threshold MD", "webcam", 20);
  cvCreateTrackbar ("Apperture", "webcam", &apperture, 2, NULL);
  cvSetTrackbarPos ("Apperture", "webcam", 0);


  // Pega um quadro só pra inicializar as paradas
  frame = cvQueryFrame (capture);
  
  output = cvCreateImage (cvGetSize (frame), IPL_DEPTH_8U, 1);
  //output->origin = output->origin; //??????????? no original

  //// Fazer float depois, e tentar usar laplaciano só por diversão
  //output = cvCreateImage (cvGetSize (frame), IPL_DEPTH_32F, 3);
  
  // Main loop
  while (frame = cvQueryFrame (capture))// Grab frame
    {
      // Convert image to greyscale and apply canny operator
      cvCvtColor (frame, output, CV_BGR2GRAY);
      cvCanny (output, output, thr1+thr2, thr1-thr2, apperture*2+3);
      //cvLaplace(frame, output, 3);
      
      cvShowImage ("webcam", output);
      
      // Process key wait (needed for OpenCV GUI)
      int c = cvWaitKey (10);
      if ((char) c == 27)
	break;
    }

  // Release all
  cvReleaseCapture (&capture);
  cvDestroyWindow ("webcam");

  return 0;
}
